package com.exam.sacrifice.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.exam.commonbiz.base.BaseActivity;
import com.exam.commonbiz.base.BaseViewModel;
import com.exam.commonbiz.base.BasicApplication;
import com.exam.commonbiz.event.IdentityExpiredEvent;
import com.exam.commonbiz.util.AppManager;
import com.exam.commonbiz.util.StatusBarUtil;
import com.exam.commonbiz.util.ToastUtil;
import com.exam.sacrifice.R;
import com.exam.sacrifice.bean.MenuInfo;
import com.exam.sacrifice.databinding.ActivityMainBinding;
import com.exam.sacrifice.event.PlayMusicEvent;
import com.exam.sacrifice.service.RawMusicService;
import com.exam.sacrifice.ui.adapter.HomeTabFragmentAdapter;
import com.exam.sacrifice.ui.login.LoginActivity;
import com.google.android.material.tabs.TabLayout;
import com.pgyersdk.update.PgyUpdateManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity<BaseViewModel, ActivityMainBinding> {

    private List<Fragment> mFragmentList;
    private static boolean isExit = false;
    private List<MenuInfo> mMenuInfoList;
    private HomeFragment mHomeFragment;
    private ZuPuTabFragment mZuPuTabFragment;
    private ActivityFragment mActivityFragment;
    public RawMusicService musicService;
    private boolean isBound = false;

    public RawMusicService getMusicService() {
        return musicService;
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            RawMusicService.MusicBinder binder = (RawMusicService.MusicBinder) service;
            musicService = binder.getService();
            isBound = true;
//            musicService.playRawResource(R.raw.music_bg);
            if (mHomeFragment != null) {
                mHomeFragment.playAnim();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        adjustBottomNavigationForVivo();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {

        initViewPager();
        initTabLayout();

        // 启动并绑定服务
        Intent serviceIntent = new Intent(this, RawMusicService.class);
        startService(serviceIntent);
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);

        new PgyUpdateManager.Builder()
                .setForced(false)              //设置是否强制更新
                .setUserCanRetry(false)        //失败后是否提示重新下载
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk
                .register();
    }

    private void initViewPager() {
        //把Fragment添加到List集合里面
        mFragmentList = new ArrayList<>();
        mMenuInfoList = new ArrayList<>();

        MenuInfo menuHome = new MenuInfo();
        menuHome.tilte = "首页";
        menuHome.iconSelect = R.drawable.home_selected;
        menuHome.iconUnSelect = R.drawable.home_unselect;

        MenuInfo menuZuPu = new MenuInfo();
        menuZuPu.tilte = "族谱";
        menuZuPu.iconSelect = R.drawable.zupu_selected;
        menuZuPu.iconUnSelect = R.drawable.zupu_unselect;

        MenuInfo menuActivity = new MenuInfo();
        menuActivity.tilte = "活动";
        menuActivity.iconSelect = R.drawable.activity_selected;
        menuActivity.iconUnSelect = R.drawable.activity_unselect;

        MenuInfo menuMine = new MenuInfo();
        menuMine.tilte = "我的";
        menuMine.iconSelect = R.drawable.mine_selected;
        menuMine.iconUnSelect = R.drawable.mine_unselect;

        mMenuInfoList.add(menuHome);
        mMenuInfoList.add(menuZuPu);
        mMenuInfoList.add(menuActivity);
        mMenuInfoList.add(menuMine);

        mHomeFragment = HomeFragment.newInstance();
        mZuPuTabFragment = ZuPuTabFragment.newInstance();
        mActivityFragment = ActivityFragment.newInstance();

        mFragmentList.add(mHomeFragment);
        mFragmentList.add(mZuPuTabFragment);
        mFragmentList.add(mActivityFragment);
        mFragmentList.add(MineFragment.newInstance());

        HomeTabFragmentAdapter mHomeTabFragmentAdapter = new HomeTabFragmentAdapter(getSupportFragmentManager(), mFragmentList, mMenuInfoList, context);
        binding.viewPager.setAdapter(mHomeTabFragmentAdapter);
        binding.viewPager.setOffscreenPageLimit(mFragmentList.size());
        binding.tabLayout.setupWithViewPager(binding.viewPager);

        for (int i = 0; i < binding.tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = binding.tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(mHomeTabFragmentAdapter.getTabView(i));
            }
        }
        binding.viewPager.setCurrentItem(0);
        onTabSelectView(binding.tabLayout.getTabAt(0));
        updateStatusBarColor(0);
    }

    private void initTabLayout() {

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 3) {
                    updateStatusBarColor(tab.getPosition());
                    binding.tabLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            onTabSelectView(tab);
                        }
                    }, 100);
                } else {
                    onTabSelectView(tab);
                    binding.tabLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            updateStatusBarColor(tab.getPosition());
                        }
                    }, 100);
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView textView = view.findViewById(R.id.tv_title);
                textView.setTextColor(getResources().getColor(R.color.color_9ca3af));
                ImageView imgIcon = view.findViewById(R.id.iv_icon);
                imgIcon.setImageResource(mMenuInfoList.get(tab.getPosition()).iconUnSelect);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //再次选中tab的逻辑
            }
        });
    }

    private void updateStatusBarColor(int position) {
        switch (position) {
            case 0: // 第一个 Fragment（红色+白色文字）
                StatusBarUtil.setLightStatusBar(this, false, true);
                break;
            case 1: // 第二个 Fragment（绿色+黑色文字）
                StatusBarUtil.setLightStatusBar(this, true, true);
                break;
            case 2: // 第三个 Fragment（蓝色+白色文字）
                StatusBarUtil.setLightStatusBar(this, true, true);
                break;
            case 3: // 第三个 Fragment（蓝色+白色文字）
                StatusBarUtil.setLightStatusBar(this, false, true);
                break;
            default:
                StatusBarUtil.setLightStatusBar(this, false, true);
                break;
        }
    }

    private void onTabSelectView(TabLayout.Tab tab) {
        MenuInfo incomeMenuInfo = mMenuInfoList.get(tab.getPosition());
        View view = tab.getCustomView();
        TextView textView = view.findViewById(R.id.tv_title);
        textView.setTextColor(getResources().getColor(R.color.main_color));
        ImageView imgIcon = view.findViewById(R.id.iv_icon);
        imgIcon.setImageResource(incomeMenuInfo.iconSelect);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void back() {

    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            showToast("再按一次退出程序");
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    private void adjustBottomNavigationForVivo() {
        if (isVivoDevice()) {
            ViewGroup.MarginLayoutParams params =
                    (ViewGroup.MarginLayoutParams) binding.tabLayout.getLayoutParams();

            // 增加底部margin
            params.bottomMargin = getNavigationBarHeight() + dpToPx(3);
            binding.tabLayout.setLayoutParams(params);
        }
    }

    private boolean isVivoDevice() {
        String manufacturer = Build.MANUFACTURER;
        return "vivo".equalsIgnoreCase(manufacturer);
    }

    private int dpToPx(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    private int getNavigationBarHeight() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Resources resources = getResources();
            int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                return resources.getDimensionPixelSize(resourceId);
            }
        }
        return 0;
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIdentityExpiredEvent(IdentityExpiredEvent event) {
        ToastUtil.getInstance().showToast("登录过期，请重新登录");
        BasicApplication.app.setToken("");
        actionStart(LoginActivity.class);
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPlayMusicEvent(PlayMusicEvent event) {
        if (!isBound) {
            return;
        }
        // 手动停止
        if (event.status == PlayMusicEvent.MUSIC_STOP) {
            musicService.stopMusic();
        }
        // 开始播放
        else if (event.status == PlayMusicEvent.MUSIC_START) {
            musicService.playRawResource(R.raw.music_bg);
        }
        // 暂停播放
        else if (event.status == PlayMusicEvent.MUSIC_PAUSE) {
            musicService.pauseMusic();
        }
        // 恢复播放
        else if (event.status == PlayMusicEvent.MUSIC_RESUME) {
            musicService.resumeMusic();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(serviceConnection);
            isBound = false;
        }
    }
}